package com.atguigu.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.atguigu.edu.entity.Subject;
import com.atguigu.edu.entity.subject.OneSubject;
import com.atguigu.edu.entity.subject.TwoSubject;
import com.atguigu.edu.excel.listener.SubjectExcelListener;
import com.atguigu.edu.excel.model.SubjectExcelData;
import com.atguigu.edu.mapper.SubjectMapper;
import com.atguigu.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-08-04
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    @Override
    public void saveSubject(MultipartFile file, SubjectService subjectService) {
        try {
            InputStream in= file.getInputStream();
            EasyExcel.read(in, SubjectExcelData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        QueryWrapper<Subject> subjectQueryWrapper = new QueryWrapper<>();
        subjectQueryWrapper.eq("parent_id","0").orderByDesc("gmt_create");
        List<Subject> oneSubjects = baseMapper.selectList(subjectQueryWrapper);
        List<OneSubject> resultList = new ArrayList<>();
        QueryWrapper<Subject> subjectQueryWrapper1 = new QueryWrapper<>();
        subjectQueryWrapper1.ne("parent_id","0").orderByDesc("gmt_create");
        List<Subject> twoSubjects = baseMapper.selectList(subjectQueryWrapper1);
        for (int i = 0; i < oneSubjects.size(); i++) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(oneSubjects.get(i),oneSubject);
            List<TwoSubject> twoSubjectList = new ArrayList<>();
            for (int j = 0; j < twoSubjects.size() ; j++) {
                if (twoSubjects.get(j).getParentId().equals(oneSubjects.get(i).getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(twoSubjects.get(j),twoSubject);
                    twoSubjectList.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjectList);
            resultList.add(oneSubject);
        }
        return resultList;
    }
}
